;(function(){
  'use strict';
  angular.module('controllers.faultLocation.failureLocation')
    .controller('failureFoundCtrl',failureFoundCtrl);

  function failureFoundCtrl($scope,FailureFoundServer,CoreService,COREDATA,System,CoreLoading){
    var sysArr = System.map(function(item){return item.systemCode;});
    var failureChart = echarts.init(document.getElementById('failureInMap'));
    var provinces = COREDATA.PROVINCES;
    var provinceArr = {};
    var titleObj = {};
    var timetemp;
    $scope.failureFound = {};
    $scope.systems = System;
    $scope.show = {};

    angular.forEach(provinces,function(province){
      provinceArr[province.provinceCode] = province.provinceName;
    });

    angular.forEach(System,function(item){
      titleObj[item.systemCode] = item.systemName;
    });

    $scope.foundFailure = function(systemCode){
      if(systemCode === sysArr.indexOf(systemCode) === -1 || systemCode === $scope.failureFound.systemCode){
        return;
      }
      $scope.failureFound.systemCode = systemCode;
      $scope.isResponded = false;
      CoreLoading.setState(true);
      FailureFoundServer.failureFound($scope.failureFound,function(res){
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0 ){
          CoreLoading.setState(false);
          CoreService.dialog(res.state);
          return;
        }
        var opt = new ChartOpt(titleObj[systemCode]);
        timetemp = res.data[0].time;
        angular.forEach(res.data, function (item) {
          switch (item.state) {
            case '1':
              if (opt.series[1].data.length >= 2) {
                opt.series[0].data.push({
                  name: provinceArr[item.provinceCode],
                  value: Number(item.businessAccount)
                });
              } else {
                opt.series[1].data.push({
                  name: provinceArr[item.provinceCode],
                  value: Number(item.businessAccount)
                });
              }
              break;
            case '2':
              opt.series[0].data.push({
                name: provinceArr[item.provinceCode],
                value: Number(item.businessAccount)
              });
              break;
            default:
              opt.series[0].data.push({
                name: provinceArr[item.provinceCode],
                value: Number(item.businessAccount)
              });
          }
        });
        $scope.isResponded = true;
        failureChart.clear();
        failureChart.setOption(opt);
        failureChart.un(echarts.config.EVENT.CLICK);
        failureChart.on(echarts.config.EVENT.CLICK,function(params){
          angular.forEach(provinceArr,function(item,key){
            if(item === params.name){
              $scope.$broadcast('drill',key,$scope.failureFound.systemCode,provinces,System,timetemp);
              $scope.show.isDrill = true;
              $scope.$apply();
            }
          });
        });
        CoreLoading.setState(false);
      });
    };

    $scope.foundFailure(sysArr[0]);

    function ChartOpt(title){
      var titleText = title+'故障发现';
      this.tooltip = {trigger : 'item'};
      this.title = {text:titleText,x:'center'};
      this.legend = {
        orient: 'vertical',
        x:'right',
        y:'center',
        data:['业务正常区域','业务预警区域','业务故障区域']
      };
      this.series = [
        {
          name:'业务正常区域',
          type:'map',
          mapType:'china',
          itemStyle:{
            normal:{
              color:'#d0d0d0',
              label:{show:true},
              borderWidth:1,
              borderColor:'#EEEEEE'
            },
          },
          data:[]
        },
        {
          name:'业务预警区域',
          type:'map',
          mapType:'china',
          itemStyle:{
            normal:{
              color:'#FF9999',
              label:{show:true,textStyle:{color:'#F5F5DC'}},
              borderWidth:1,
              borderColor:'#EEEEEE'
            }
          },
          data:[]                     
        },
        {
          name:'业务故障区域',
          type:'map',
          mapType:'china',
          itemStyle:{
            normal:{
              color:'#EE2C2C',
              label:{show:true,textStyle:{color:'#F5F5DC'}},
              borderWidth:1,
              borderColor:'#EEEEEE'
            }
          },
          data:[]                     
        },
      ];
    }
  }

  failureFoundCtrl.$inject = ['$scope','FailureFoundServer','CoreService','COREDATA','System','CoreLoading'];
})();


;(function(){
  angular.module('controllers.faultLocation.failureLocation')
    .controller('failureOrientateCtrl',failureOrientateCtrl);
  function failureOrientateCtrl($scope,CoreServer,$timeout,FailureFoundServer,CoreService,COREDATA,CoreLoading){
    var queryedSystem = '';
    var locateFailureChart = echarts.init(document.getElementById('locateFailure'));
    var realTimeChart = echarts.init(document.getElementById('realTimeChart'));
    var businessUsability = echarts.init(document.getElementById('businessUsability'));
    var allFieldParam = {};

    $scope.toggle = false;
    $scope.orientate = {};
    $scope.startTime = new Date();
    $scope.endTime = new Date();
    $scope.selector = {
      systemCode:COREDATA.SYSTEM,
      provinces:COREDATA.PROVINCES,
      businessCode:[]
    };
    
    $scope.goBack = function(){
      $scope.show.isDrill = false;
      $scope.show.usability = false;
      $scope.show.orientate = false;
      $scope.show.succeedByIp = false;
      $scope.isQuery = false;
      locateFailureChart.clear();
    };

    $scope.getBusinesses = function(systemCode){
      if(queryedSystem === systemCode){
        return;
      }
      if($scope.selector.businessCode.length !== 0){
        return;
      }
      return CoreServer.getSysBusiness({systemCode:systemCode.systemCode},function(res){
        if(res.state === '10000'){
          $scope.selector.businessCode = res.data;
          queryedSystem = $scope.orientate.systemCode;
        }
      });
    };

    $scope.getNames = function(series,objName,propertyName){
      if(is.array(series[objName])){
        if(series[objName].length === $scope.selector[objName].length){
          return '全部';
        }
        var namesArr = series[objName].map(function(item){
          if(!item){
            return undefined;
          }
          return item[propertyName];
        });
        return namesArr.join(',');
      } else {
        return series[objName][propertyName];
      }
    };

    $scope.checkAll = function(series,propertyName){
      $timeout(function(){series[propertyName] = undefined;});
    };

    $scope.$on('drill',function(d,provinceCode,systemCode,provinces,systems,timetemp){
      angular.forEach(provinces,function(item){
        if(item.provinceCode === provinceCode){
          $scope.orientate.provinceCode = item;
        }
      });
      angular.forEach(systems,function(item){
        if(item.systemCode === systemCode){
          $scope.orientate.systemCode = item;
        }
      });
      $scope.selector.provinceCode = provinces;
      $scope.startTime = new Date(timetemp);
      failureRealtime($scope.orientate.provinceCode,$scope.orientate.systemCode);
    });

    $scope.busSucceedByIp = function(){
      var charts = {};
      FailureFoundServer.busSucceedByIp(allFieldParam,function(res){
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
          CoreService.dialog('下钻查询失败');
        }
        $scope.succeedByIp = res.data;       
        $timeout(setBusinessByIpChart(charts,res.data),0);
      });
    };

    $scope.locateFailure = function(){
      var param = processParam($scope.orientate);
      if($scope.toggle){
        if($scope.orientateForm.$invalid || !$scope.orientate.businessCode){
          return;
        }
        CoreLoading.setState(false);
        FailureFoundServer.failureOrientate(param,function(res){   
          var opt = {};
          var title = '';
          if(res.state === '10000' && res.data.length >= 1 ){
            allFieldParam = param;
            title = getPABName()+'办理成功量趋势';
            opt = getSucceedBusinessChartOpt(res.data,title);
            locateFailureChart.clear();
            locateFailureChart.setOption(opt);
            CoreLoading.setState(false);
            $scope.isQuery = true;
            $scope.show.usability = false;
            $scope.show.orientate = true;
            $scope.show.succeedByIp = false;
            $scope.show.phasePosition = false;
            $scope.toggle = !$scope.toggle;
          }else{
            CoreLoading.setState(false);
            CoreService.dialog(res.state);
          }
        });
      }else{
        $scope.toggle = !$scope.toggle;
      }
    };

    $scope.downToUsability = function(){
      var opt = {};
      CoreLoading.setState(true);
      FailureFoundServer.businessUsability(allFieldParam,function(res){
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
          CoreLoading.setState(false);
          CoreService.dialog('下钻查询失败');
        }
        opt = getBusAbilityOpt(res.data,getPABName()+'可用性实时数据');
        businessUsability.setOption(opt);
        CoreLoading.setState(false);
        $scope.show.usability = true;
        $scope.show.orientate = false;
        $scope.show.succeedByIp = false;
        $scope.show.phasePosition = false;
      }); 
    };

    $scope.phasePositon = function(){
      var param = {};
      var charts = {};
      angular.copy(allFieldParam,param);
      // param.ip = ip;  
      CoreLoading.setState(true);
      FailureFoundServer.phasePosition(param,function(res){
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
          CoreLoading.setState(false);
          CoreService.dialog('下钻查询失败');
        }
        $scope.phaseUsability = res.data;
        $timeout(setPhaseUsability(charts,res.data),0);
        CoreLoading.setState(false);
      });

    };

    function failureRealtime(provinceCode,systemCode){
      var param = {systemCode:systemCode.systemCode,provinceCode:provinceCode.provinceCode};
      var xAxisData = [],seriesData = [];
      CoreLoading.setState(true);
      FailureFoundServer.failureRealtime(param,function(res){
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
          CoreLoading.setState(false);
          CoreService.dialog('查询实时业务异常');
          return;
        }
        angular.forEach(res.data,function(item,index){
          xAxisData.push(index);
          seriesData.push(item.businessAccount);
        });
        realTimeChart.clear();
        realTimeChart.setOption(new RealTimeOpt(xAxisData,seriesData));
        CoreLoading.setState(false);
      });

      function RealTimeOpt(xAxisData,seriesData){
        this.title = {
          text:'故障发现分析',
          x:'center'
        };
        this.xAxis = [
          {
            type: 'category',
            boundaryGap: false,
            data: xAxisData,
            name:'分'
          }
        ];
        this.animation = false;
        this.yAxis = [
          {type: 'value'}
        ];
        this.series = [
            {
                name: '业务实时成功量',
                type: 'line',
                data: seriesData,
                smooth:true,
                symbolSize:0,
                clickAble:false,
                itemStyle: {normal: {areaStyle: {type: 'default',color:'rgba(237,246,231,0.6)'},color:'#B5DA9A'}}
            }
        ];
      }
    }

    function processParam(originParam){
      var param = {};
      param.systemCode = originParam.systemCode.systemCode;
      param.provinceCode = originParam.provinceCode.provinceCode;
      if(originParam.businessCode){
        param.businessCode = originParam.businessCode.businessCode;
      }else{
        param.businessCode = '';
      }
      param.time = CoreService.dateFormat($scope.startTime,'yyyy-MM-dd hh:mm:ss');
      return param;
    }

    function ChartOpt(title,seriesData,scatterData,max,xAxisData){
      this.title = {
        text:title,
        x:'center'
      };
      this.xAxis = [
        {
          type:'category',data:xAxisData,boundaryGap:false
        },
        {
          type:'category', data:xAxisData,boundaryGap:false, axisLabel: {show:false},axisLine:{show:false},axisTick:{show:false}
        }    
      ];
      this.legend = {selectedMode:false,show:true,orient:'vertical',data:['实时散点','实时趋势'],y:'center',x:'right'};
      this.tooltip = {show:true,formatter:function(params){
        if(params.seriesName.substr(2,2) === '趋势'){
          return params.seriesName+':<br>'+params.value;
        }else{
          return params.seriesName+':<br>'+params.value[1];
        }
      }};
      this.animation = false;
      this.grid = {x2:120};
      this.yAxis = [ 
        {
          type : 'value',splitLine: {show:false},max:max
        },
        {
          type : 'value',splitLine: {show:false},max:max,axisLine:{show:false},axisTick:{show:false}, axisLabel: {show:false}
        }
      ];
      this.series = [{
        clickable:false,name:'实时散点',type:'scatter',data:scatterData, yAxisIndex:1,xAxisIndex:1,symbol:'circle',symbolSize:3,itemStyle:{normal:{color:'#F44336'},emphasis: {color: 'rgba(0,0,0,0)'}}
      },{
        clickable:false,name:'实时趋势',type:'line',data:seriesData,symbolSize:0,itemStyle:{normal:{color:'#F44336'},emphasis: {color: 'rgba(0,0,0,0)'}}
      }];
    }

    function getSucceedBusinessChartOpt(data,title){
      var max = 0;
      var count = 1;
      var dataArr = [];
      var avgArr = [];
      var scatterAvg = []; 
      var scatterData = [];
      var xAxisData = []; 
      var opt = {};
      angular.forEach(data,function(item,key){
        var x = Math.floor(key/2)+(key%2 > 0 ? ':30':':00');
        var movingAvg;
        var historyAvg;
        if(key === 0 ){
          movingAvg = Math.round((Number(data[key].businessAccount)*2+Number(data[key+1].businessAccount))/3);
          historyAvg = Math.round((Number(data[key].avg)*2+Number(data[key+1].avg))/3);
        } else if (key === data.length-1){
          movingAvg = Math.round((Number(data[key-1].businessAccount)+Number(data[key].businessAccount)*2)/3);
          historyAvg = Math.round((Number(data[key-1].avg)+Number(data[key].avg)*2)/3);
        }else{
          movingAvg = Math.round((Number(data[key-1].businessAccount)+Number(data[key].businessAccount)+Number(data[key+1].businessAccount))/3);
          historyAvg = Math.round((Number(data[key-1].avg)+Number(data[key].avg)+Number(data[key+1].avg))/3);
        }
        max = max >= Number(item.businessAccount) ? max : Number(item.businessAccount);           
        max = max >= Number(item.avg) ? max : Number(item.avg);
        scatterData.push([x,Number(item.businessAccount)]);
        scatterAvg.push([x,Number(item.avg)]);
        dataArr[key] = movingAvg;
        avgArr[key] = historyAvg;
        xAxisData.push(x);
      });
      while(max > 10){
        max = max/10;
        count = count*10;
      }
      max = Math.ceil(max);
      opt = new ChartOpt(title,dataArr,scatterData,max*count,xAxisData);
      opt.series[2] = {};
      opt.series[3] = {};
      angular.copy(opt.series[0],opt.series[2]);
      angular.copy(opt.series[1],opt.series[3]);
      opt.series[2].data = scatterAvg;
      opt.series[2].name = '历史散点';
      opt.series[3].data = avgArr;
      opt.series[3].name = '历史趋势';
      opt.series[2].itemStyle = {normal:{color:'#2196F3'}};
      opt.series[3].itemStyle = {normal:{color:'#2196F3'}};
      opt.legend.data.push('历史散点');
      opt.legend.data.push('历史趋势');
      return opt;         
    }
    
    
    function getBusAbilityOpt(data,title){
      var xAxisData = [];
      var seriesData = [[],[]];
      var opt = {};
      angular.forEach(data,function(item,index){
        xAxisData.push(index);
        seriesData[0].push([index,item.usabilityMax]);
        seriesData[1].push([index,item.usabilityMin]);
      });
      opt = new BusAbilityOpt(title,xAxisData,seriesData);
      return opt;
    }
    
    function BusAbilityOpt(title,xAxisData,seriesData){
      this.title = {
          text:title,
          x:'center'
        };
      this.xAxis = [
        {
          type: 'category',
          boundaryGap: true,
          data: xAxisData,
          name:'小时'
        }
      ];
      this.yAxis = [
        {type: 'value',max:100,name:'可用性'}
      ];
      this.animation = false;
      this.series = [
          {
              name: '业务实时可用性峰值',
              type: 'scatter',
              data: seriesData[0],
              symbol:'circle',
              symbolSize:3,
              clickAble:false,
              itemStyle: {normal: {color:'#5397D3'}}
          },
          {
              name: '业务实时可用性低谷',
              type: 'scatter',
              data: seriesData[1],
              symbol:'circle',
              symbolSize:3,
              clickAble:false,
              itemStyle: {normal: {color:'#5397D3'}}
          }
      ];
    }

    function setBusinessByIpChart(charts,data){
      return function(){
        for(var i=0,id='succeedByIp';i<data.length;i++){
          charts[i] = echarts.init(document.getElementById(id+i));
        }
        angular.forEach(data,function(item,key){
          var title = getPABName()+'办理成功量趋势实时数据'+item.ip;
          debugger;
          var opt = getSucceedBusinessChartOpt(item.data,title);
          charts[key].clear();
          charts[key].setOption(opt);
        });
        $scope.show.orientate = false;
        $scope.show.usability = false;
        $scope.show.succeedByIp = true;
        $scope.show.phasePosition = false;
      };
    }

    function setPhaseUsability(charts,data){
      return function(){
        for(var i=0,id='phasePosition';i<data.length;i++){
          charts[i] = echarts.init(document.getElementById(id+i));
        }
        angular.forEach(data,function(item,key){
          var title = item.phaseName;
          var opt = getBusAbilityOpt(item.data,title);
          charts[key].clear();
          charts[key].setOption(opt);
        });
        $scope.phaseTitle = getDuration(allFieldParam.time)+getPABName()+'各环可用性统计';
        $scope.show.orientate = false;
        $scope.show.usability = false;
        $scope.show.succeedByIp = false;
        $scope.show.phasePosition = true;
      };
    }

    function getPABName(){
      var title = '';
      angular.forEach($scope.selector.provinceCode,function(item){
        if(item.provinceCode === allFieldParam.provinceCode){
          title = item.provinceName;
        }
      });
      if(allFieldParam.businessCode){
        angular.forEach($scope.selector.businessCode,function(item){
          if(item.businessCode === allFieldParam.businessCode){
            title = title + item.businessName + '业务';
          }
        });
      }else{
        title = title + '全业务';
      }
      return title;
    }

    function getDuration(time){
      var year = time.substr(0,4);
      var month = time.substr(5,2);
      var day = Number(time.substr(8,2));
      var begin = CoreService.dateFormat(new Date(year,month,day-2),'yyyy-MM-dd');
      var end = CoreService.dateFormat(new Date(year,month,day-1),'yyyy-MM-dd');
      return begin+'~'+end;
    }
  }

  failureOrientateCtrl.$inject = ['$scope','CoreServer','$timeout','FailureFoundServer','CoreService','COREDATA','CoreLoading'];
})();